//
//  AppDelegate.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/8.
//
#import "AppDelegate.h"
#import "LiXingMainTabbarVC.h"
#import "LoginPageViewController.h"
#import "AppDelegate+Net.h"
#import "WOCrashProtectorManager.h"
#import "AppDelegate+JPush.h"
#import "PersonInfoViewController.h"
#import "SuoShuQiYeViewController.h"
#import "RCChatroomMessageCenter.h"
#import "LXMessageRepairCarInfo.h"
#import "JPUSHService.h"
#import <PushKit/PushKit.h>
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
//友盟
#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>
#import <Bugly/Bugly.h>

#import <Pingpp.h>

@interface AppDelegate ()<RCIMUserInfoDataSource,RCIMGroupInfoDataSource,RCIMGroupUserInfoDataSource,UNUserNotificationCenterDelegate,WXApiDelegate>
@end
@implementation AppDelegate

+ (instancetype)shareDelegete{
    
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions {
    [WOCrashProtectorManager makeAllEffective];
    [AppDelegate monitorNetworking];
    [AppDelegate netCfg];
    [Bugly startWithAppId:@"58962a2ff5"];
    //融云
    [[RCIM sharedRCIM] initWithAppKey:RongIM_APPID];
//    [[RCIMClient sharedRCIMClient] initWithAppKey:RongIM_APPID];
    [RCChatroomMessageCenter registerMessageTypes];
    [[RCIM sharedRCIM] registerMessageType:[LXMessageRepairCarInfo class]];
   
    
    [RCIM sharedRCIM].userInfoDataSource = self;
    [RCIM sharedRCIM].groupInfoDataSource = self;
    
    [self requestPicHost];
    
    if (userIsLogin) {
        [self requestIM_token];
    }
   
    
    //极光
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert | JPAuthorizationOptionBadge | JPAuthorizationOptionSound | JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert | JPAuthorizationOptionBadge | JPAuthorizationOptionSound;
    }
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:APPKEY_JPUSH channel:@"App Store" apsForProduction:NO advertisingIdentifier:nil];
    
    
    
    
    if (@available(iOS 11.0, *)) {
        [UITableView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        [UITableView appearance].sectionHeaderTopPadding = 0;
    }
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                //点击允许
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    
                }];
                
            } else {
                
            }
        }];
    }
    [application registerForRemoteNotifications];
    
    
    //友盟分享
    [UMConfigure initWithAppkey:U_SHARE_APPKEY channel:@"App Store"];
    [UMConfigure setLogEnabled:YES];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_APPID appSecret:WX_AppSecret redirectURL:@"http://mobile.umeng.com/social"];
  
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_APPID appSecret:WX_AppSecret redirectURL:nil];

    /* 设置QQ */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQ_APPID/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"https://www.lixingpt.com/qq_conn/1112132958"];

    /* 设置微信朋友圈 */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:WX_APPID  appSecret:WX_AppSecret redirectURL:nil];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine|UMSocialPlatformType_WechatSession appKey:WX_APPID  appSecret:WX_AppSecret redirectURL:nil];
    
    [WXApi registerApp:WX_APPID universalLink:@"https://www.lixingpt.com/"];

    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    return YES;
}



- (void)requestPicHost
{
 
    NSString *url = [NSString stringWithFormat:@"%@%@",DOMAIN_URL,Host_Url];
    [MSNetworkManager getRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            [[MSStorageUtils shareInstance] userDefaultSave:resonseObj withKey:USER_DEFAULT_HOST_URL];
        }
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:NO];
    
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
//    [NSThread sleepForTimeInterval:3.0];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
    YLUserInfo *info = [YLUserMgr fetchUser];
    //info.enterpriseName.length == 0 || info.realName.length == 0 ||
    // token 为空
    if (info.authorization.length == 0) {
        LoginPageViewController *pageVC = [[LoginPageViewController  alloc] init];
        UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:pageVC];
        [self.window setRootViewController:navigationVC];
        [self.window makeKeyAndVisible];
    }
    // token 不为空 没有实名
    else if (info.authorization.length > 0 && info.realName.length < 1) {
        PersonInfoViewController *vc = [[PersonInfoViewController alloc] init];
        UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:vc];
        [self.window setRootViewController:navigationVC];
        [self.window makeKeyAndVisible];
    }
    else if ((info.realName.length > 0 && [NSString stringWithFormat:@"%@",info.companyId].length < 1) || [NSString isempty:[NSString stringWithFormat:@"%@",info.companyId]] || [info.companyId intValue] < 1) {
        LoginPageViewController *pageVC = [[LoginPageViewController  alloc] init];
        UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:pageVC];
        [self.window setRootViewController:navigationVC];
        [self.window makeKeyAndVisible];
    } else if (info.authorization.length > 0 && [NSString stringWithFormat:@"%@",info.companyId].length > 0 && info.realName.length > 0){
        LiXingMainTabbarVC *tabBarController = [[LiXingMainTabbarVC alloc] init];
        tabBarController.delegate = self;
        tabBarController.selectedIndex = 0;
        [self.window setRootViewController:tabBarController];
        [self.window makeKeyAndVisible];
    }
    
    return YES;
}

- (void)requestIM_token
{
    
    NSString *url = [DOMAIN_URL stringByAppendingString:GET_GetRongToken];
    [MSNetworkManager getRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            [[RCIM sharedRCIM] connectWithToken:resonseObj[@"token"]
                                       dbOpened:^(RCDBErrorCode code) {
            }
                                        success:^(NSString *userId) {
                RCUserInfo *_currentUserInfo = [[RCUserInfo alloc] initWithUserId:USER_IM_TOKEN name:USER_REAL_NAME portrait:USER_HEAD_IMAGE];
                [RCIM sharedRCIM].currentUserInfo = _currentUserInfo;

            }
                                          error:^(RCConnectErrorCode status) {
                if (status == RC_CONN_TOKEN_INCORRECT) {
                    //从 APP 服务获取新 token，并重连
                } else {
                    //无法连接到 IM 服务器，请根据相应的错误码作出对应处理
                }
            }];

        }
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:NO];
    
    
 
 
}
//群组信息
- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *))completion{
    completion(nil);
   
}
// 用户信息
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion
{
    
    if ([userId isEqualToString:USER_IM_TOKEN]) {
        RCUserInfo *info = [[RCUserInfo alloc] init];
        info.name = USER_REAL_NAME;
        info.portraitUri = USER_HEAD_IMAGE;
        info.userId = USER_IM_TOKEN;
        completion(info);
    }
    else {
        
        [MSNetworkManager getRevertUrl:[DOMAIN_URL stringByAppendingString:GET_GetUserInfoById] params:@{@"toAccount":userId} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if(isSuccess){
                RCUserInfo *info = [[RCUserInfo alloc] init];
                info.name = resonseObj[@"nickname"];
                info.portraitUri = resonseObj[@"headImgurl"];
                info.userId = resonseObj[@"toAccount"];
                completion(info);
                
            }
            else {
                completion(nil);
            }
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            
        } withShowHud:NO];
    }
}
#pragma mark - 进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
}
#pragma mark - 将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // 融云
    [[RCIMClient sharedRCIMClient] setDeviceTokenData:deviceToken];
    // 极光
    [JPUSHService registerDeviceToken:deviceToken];
   

}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"%@",userInfo);
}
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void(^)(void))completion{
    // 提交回执给极光服务器
    [JPUSHService handleVoipNotification:payload.dictionaryPayload];
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
  NSDictionary * userInfo = notification.request.content.userInfo;
  UNNotificationRequest *request = notification.request; // 收到推送的请求
  UNNotificationContent *content = request.content; // 收到推送的消息内容
  
  NSNumber *badge = content.badge;  // 推送消息的角标
  NSString *body = content.body;    // 推送消息体
  UNNotificationSound *sound = content.sound;  // 推送消息的声音
  NSString *subtitle = content.subtitle;  // 推送消息的副标题
  NSString *title = content.title;  // 推送消息的标题
  
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  } else {
      
}
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
   
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}

- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
  [self alertNotificationAuthorization:status];
}



#pragma mark- PKPushRegistryDelegate

/// 系统返回VoipToken,上报给极光服务器
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)pushCredentials forType:(PKPushType)type{
    [JPUSHService registerVoipToken:pushCredentials.token];
    NSLog(@"Voip Token: %@", pushCredentials.token);
}
// 通知未授权时提示，是否进入系统设置允许通知，仅供参考
- (void)alertNotificationAuthorization:(JPAuthorizationStatus)status {
    if (status < JPAuthorizationStatusAuthorized&&[[NSUserDefaults standardUserDefaults] boolForKey:@"isNotiSend"]==NO) {
        [[NSUserDefaults standardUserDefaults] setBool:YES  forKey:@"isNotiSend"];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"允许通知" message:@"是否进入设置允许通知？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{}completionHandler:^(BOOL success) {}];
            
        }];
        UIAlertAction *cancelAntion = [UIAlertAction actionWithTitle:@"不允许" style:(UIAlertActionStyleDefault) handler:nil];
        
        [alertController addAction:okAction];
        [alertController addAction:cancelAntion];
        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    }
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
    NSString *title = nil;
    if (notification) {
        title = @"从通知界面直接进入应用";
    }else{
        title = @"从系统设置界面进入应用";
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"去设置" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:okAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
   
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSLog(@"授权结果 result = %@", result?:@"");
        }];
        
      
    }
    
    if([url.host isEqualToString:@"platformId=wechat"]){
        BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
        NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
        return  isSuc;
    }
    
    if ([Pingpp handleOpenURL:url withCompletion:nil]) {
        return YES;
    }
    
    return YES;
}
- (void)onResp:(BaseResp *)resp
{
    SendAuthResp *rp = (SendAuthResp *)resp;
    // 分享结果回调
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
    }
    NSLog(@"onresp = %@",resp);
}
- (void)onReq:(BaseReq *)req
{
    NSLog(@"onreq = %@",req);
}
@end
